package ee.android.kinokavad.fragments;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.joda.time.DateTime;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.viewpagerindicator.TitlePageIndicator;

import ee.android.kinokavad.App;
import ee.android.kinokavad.R;
import ee.android.kinokavad.data.Cinema;
import ee.android.kinokavad.interfaces.OnMovieClickListener;
import ee.android.kinokavad.utils.NetworkUtils;
import ee.android.kinokavad.utils.Utils;

public class MainFragmentKinoKavad extends SherlockFragment implements OnClickListener, OnMovieClickListener {

	private static final String TAG = MainFragmentKinoKavad.class.getSimpleName();
	public static final String [] DAYS = new String [] {"Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev", "Pühapäev"};
	private static List<Cinema> mCinemas;
	private static DateTime mDateTime;
	private App kinokavad;
	private TextView mDateView;
	private DateTime mMaxDate;
	private ImageView mNextDate;
	private ImageView mPreviousDate;
	private OnMovieClickListener mListener;

	
	public static Fragment newInstance(Bundle args) {
		Fragment f = new MainFragmentKinoKavad();
		f.setArguments(args);
		return f;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.main_fragment, container, false);
		
		return view;
	}
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		init();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.sessions_menu, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	private void initViews() {

		ViewPager viewPager = (ViewPager) getView().findViewById(R.id.kinokavadViewPager);
		viewPager.setAdapter(new KKFragmentPagerAdapter());
		viewPager.setPageMargin(30);
		
		TitlePageIndicator mIndicator = (TitlePageIndicator) getView().findViewById(R.id.indicator);
		mIndicator.setViewPager(viewPager);
		mIndicator.setSelectedBold(true);
		
		mDateView = (TextView) getView().findViewById(R.id.mainDatePickerDate);
		mNextDate = (ImageView) getView().findViewById(R.id.mainDatePickerNext);
		mPreviousDate = (ImageView) getView().findViewById(R.id.mainDatePickerPrevious);

		mNextDate.setOnClickListener(this);
		mPreviousDate.setOnClickListener(this);
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		getSherlockActivity().getSupportActionBar().setSubtitle("Seansid");
		initViews();
		initDate();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.mainDatePickerNext:
			handleDateSelect(mDateTime.plusDays(1));
			break;
		case R.id.mainDatePickerPrevious:
			handleDateSelect(mDateTime.minusDays(1));
			break;

		default:
			break;
		}
	}	


	private void showView(ImageView view) {
		view.setEnabled(true);
		if (view.getVisibility() != View.VISIBLE) {
			Animation animation = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
					Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
			animation.setDuration(500);
			view.startAnimation(animation);
			view.setVisibility(View.VISIBLE);
		}

	}
	private void hideView(final ImageView view) {
		view.setEnabled(false);
		if (view.getVisibility() != View.INVISIBLE) {

			Animation animation = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
					Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
			animation.setDuration(500);
			view.startAnimation(animation);
			animation.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {}
				@Override
				public void onAnimationRepeat(Animation animation) {}
				@Override
				public void onAnimationEnd(Animation animation) {
					view.setVisibility(View.INVISIBLE);
				}
			});
		}
	}

	private void handleDateSelect(DateTime dateTime) {
		mDateTime = dateTime;
		if (App.LOCAL_LOG) 
			Log.v(TAG, "Selected date: " + mDateTime.toString());
		if (mDateTime.isAfterNow()) {
			showView(mPreviousDate);
		} else {
			hideView(mPreviousDate);
		}

		if (mDateTime.plusDays(1).isAfter(mMaxDate)) {
			hideView(mNextDate);
		} else {
			showView(mNextDate);
		}

		setDateViewText();

		reloadSessions();

	}

	private void reloadSessions() {
		for (int i = 0; i < mCinemas.size(); i++) {
			String tag = Utils.fragmentTagFromViewPager(R.id.kinokavadViewPager, i);
			SessionsFragment f = (SessionsFragment) getChildFragmentManager().findFragmentByTag(tag);
			if (f != null) {
				f.loadSessions(mDateTime);
			}
		}
	}

	private void setDateViewText() {
		mDateView.setText(DAYS[mDateTime.getDayOfWeek()-1] + ", " + mDateTime.toString("dd.MM"));
	}

	private void initDate() {
		if (mDateTime == null) mDateTime = DateTime.now().withTimeAtStartOfDay();

		setDateViewText();

		kinokavad.getDataController().open();
		mMaxDate = kinokavad.getDataController().loadMaxDateFromSessions();
		kinokavad.getDataController().closeRequest();

		if (mDateTime.plusDays(1).isAfter(mMaxDate)) {
			hideView(mNextDate);
		}
		if (mDateTime.isAfterNow()) {
			showView(mPreviousDate);
		}
	}

	private void init() {

		kinokavad = (App) getActivity().getApplicationContext();
		mCinemas = new ArrayList<Cinema>();
		kinokavad.getDataController().open();
		List<Cinema> cinemas = kinokavad.getDataController().loadAllCinemasFromDatabase();
		if (cinemas.size() == 0) {
			cinemas = NetworkUtils.downloadAllCinemas(getActivity());
			for (Cinema cinema : cinemas) {
				kinokavad.getDataController().addCinemaToDatabase(cinema);
			}
		} 
		kinokavad.getDataController().closeRequest();

		for (Cinema cinema: cinemas) {
			if (cinema.isSelected()) {
				mCinemas.add(cinema);
			}
		}
		
	}

	private class KKFragmentPagerAdapter extends FragmentPagerAdapter {

		public KKFragmentPagerAdapter() {
			super(getChildFragmentManager());
		}

		@Override
		public Fragment getItem(int position) {
			
			long cinemaId = mCinemas.get(position).getNetId();
			String date = mDateTime.toString("yyyy-MM-dd");
			
			Bundle args = new Bundle();
			args.putString("date", date);
			args.putLong("cinemaId", cinemaId);
			
			return SessionsFragment.newInstance(args);
		}

		@Override
		public int getCount() {
			return mCinemas.size();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			if (position >= mCinemas.size()) {
				return "";
			}
			return mCinemas.get(position).getName().toUpperCase(Locale.ENGLISH);
		}

	}

	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnMovieClickListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnMovieClickListener");
		}
	}
	
	@Override
	public void onMovieClicked(long movieId) {
		mListener.onMovieClicked(movieId);
	}

}
